﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TransformCost.Question;

namespace TransformCost.Answer
{
    class Bob : ITransformCost
    {

        public int GetMinExchanges(int[] source, int[] target)
        {
            Dictionary<int, Queue<int>> pos = new Dictionary<int, Queue<int>>();

            for (int i = 0; i < source.Length; i++)
            {
                if (!pos.ContainsKey(source[i]))
                {
                    pos[source[i]] = new Queue<int>();
                }
                pos[source[i]].Enqueue(i);
            }
            int res = 0;
            List<int> exchangedPos = new List<int>();

            for (int i = 0; i < target.Length - 1; i++)
            {
                int oldPos = pos[target[i]].Dequeue();
                var afterCount = exchangedPos.Count(n => n > oldPos);
                res += Math.Abs(oldPos + afterCount - i);
                exchangedPos.Add(oldPos);
            }

            return res;
        }
    }

}
